<script setup>
	import { watch, ref, computed, onMounted, onActivated } from 'vue'
	import { storeToRefs } from 'pinia'
	import { showToast } from 'vant'

	import navBar from './components/nav-bar.vue'
	import bannerVant from './components/banner-vant.vue'
	import navCategories from './components/nav-categories.vue'
	import navSearch from './components/nav-search.vue'
	import hotContent from './components/hot-content.vue'
	import searchBar from '@/components/search-bar/search-bar.vue'

	import { useHomeStore } from '@/stores/modules/home'
	import useScroll from '@/hooks/useScroll.js'

	const homeStore = useHomeStore()
	onMounted(() => {
		getAction()
	})

	const getAction = () => {
		homeStore.hotSuggestsAction()
		homeStore.categotiesAction()
		homeStore.houselistAction()
	}

	// 向传入hooks回调函数
	// useScroll(() => {
	// 	homeStore.houselistAction()
	// })
	const homeRef = ref()
	const { isReachCallback, scrollTop } = useScroll(homeRef)
	watch(isReachCallback, (newValue) => {
		if (newValue) {
			homeStore.houselistAction().then(() => {
				// 获取到数据关闭滚动刷新
				isReachCallback.value = false
			})
		}
	})

	// 搜索显示的控制
	// const isShowBar = ref(false)
	// watch(scrollTop, (newValue) => {
	// 	isShowBar.value = newValue > 500
	// })
	const isShowBar = computed(() => {
		return scrollTop.value >= 500
	})
	// 跳转回home时保留原谅位置
	onActivated(() => {
		homeRef.value?.scrollTo({
			top: scrollTop.value,
		})
	})

	// 发送网络请求
	// 1.热门建议
	// const hotSuggests = ref([])
	// XBRequest.get({
	// 	url: '/home/hotSuggests.json',
	// }).then((res) => {
	// 	hotSuggests.value = res.data
	// })
	// // 2.热门建议
	// const categoties = ref([])
	// XBRequest.get({
	// 	url: '/home/categories.json',
	// }).then((res) => {
	// 	categoties.value = res.data
	// })

	const loading = ref(false)
	const { hotSuggests, categoties, currentPage, houselist } =
		storeToRefs(homeStore)
	const onRefresh = () => {
		setTimeout(() => {
			hotSuggests.value = []
			categoties.value = []
			houselist.value = []
			currentPage.value = 1
			loading.value = false
			getAction()
			showToast('刷新成功')
		}, 1000)
	}
</script>

<template>
	<div
		class="home"
		ref="homeRef">
		<van-pull-refresh
			v-model="loading"
			@refresh="onRefresh">
			<div class="nav">
				<nav-bar v-if="!isShowBar"></nav-bar>
				<search-bar v-else-if="isShowBar"></search-bar>
			</div>
			<div class="content">
				<banner-vant></banner-vant>
				<nav-search></nav-search>
				<nav-categories></nav-categories>
				<hot-content></hot-content>
			</div>
		</van-pull-refresh>
		<van-back-top
			right="30px"
			bottom="100px" />
	</div>
</template>

<style lang="scss" scoped>
	.home {
		height: 100vh;
		overflow-y: auto;
		box-sizing: border-box;
		padding-bottom: 100px;
		.content {
			margin-top: 46px;
		}
	}
</style>
